<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	private $_id;
	public function authenticate()
	{
// 		$user=Admin::model()->find('LOWER(login_name)=? and password=md5(concat(?,salt))',array(strtolower($this->username),md5($this->password)));
		$user=Admin::model()->find('LOWER(login_name)=? and password=?',array(strtolower($this->username),md5($this->password)));
		if($user===null){
			return false;
		}
		else
		{
		    //写回登录日志
		    $adminLogModel = new AdminLogs;
		    $adminLogModel->attributes = array(
    	        'admin_id'	=>    $user->admin_id,
    	        'message'	=>    Yii::t('system', 'admin_login_log',array(
    	            '{ip}'	=>    Yii::app()->request->getUserHostAddress(),
    	            '{browser}'=>    Yii::app()->request->getUserAgent()
    	        ))
    	    );
		    $adminLogModel->save(true,array('admin_id','message'));
		    
		    //获取权限
		    $permission = AdminGroupfiles::model()->findAll('group_id=?',array($user->group_id));
		    $allowPath = array();
		    foreach($permission as $p){
		        $allowPath[] = $p->permission->file_path;
		    }
		    $cookie = new CHttpCookie('allow_path', implode('|',$allowPath));
            Yii::app()->request->cookies['allow_path'] = $cookie;
			$this->_id=$user->admin_id;
			$this->setState('userInfo',$user);
			
			//将登录信息写回Admin表 
		    $user->setIsNewRecord(false);
		    $user->attributes = array(
		        'last_login_time' => Func::get_datetime(),
		    	'last_login_ip' => Func::get_ip('int')
		    );
		    $user->save( true,array('last_login_time','last_login_ip') );
			return true;
		}
	}
	public function getId()
    {
        return $this->_id;
    }
}